<template>
  <div class="sales-record-management">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>商品售卖记录</span>
          <el-button type="primary" @click="showAddDialog">
            <el-icon><Plus /></el-icon>
            添加售卖记录
          </el-button>
        </div>
      </template>

      <!-- 搜索表单 -->
      <el-form :model="searchForm" :inline="true" class="search-form">
        <el-form-item label="记录编号">
          <el-input
            v-model="searchForm.recordNo"
            placeholder="请输入记录编号"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="商品名称">
          <el-input
            v-model="searchForm.productName"
            placeholder="请输入商品名称"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="客户姓名">
          <el-input
            v-model="searchForm.customerName"
            placeholder="请输入客户姓名"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="售卖状态">
          <el-select
            v-model="searchForm.saleStatus"
            placeholder="请选择状态"
            clearable
            style="width: 150px"
          >
            <el-option label="已完成" :value="1" />
            <el-option label="已取消" :value="2" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch" :icon="Search">搜索</el-button>
          <el-button @click="handleReset">重置</el-button>
          <el-button type="success" @click="handleExport">导出</el-button>
        </el-form-item>
      </el-form>

      <!-- 数据表格 -->
      <el-table
        :data="tableData"
        v-loading="loading"
        style="width: 100%"
        empty-text="暂无数据"
      >
        <el-table-column prop="recordNo" label="记录编号" width="180" />
        <el-table-column prop="productName" label="商品名称" width="150" />
        <el-table-column prop="productCode" label="商品编号" width="120" />
        <el-table-column prop="saleQuantity" label="售卖数量" width="100" align="center" />
        <el-table-column prop="unitPrice" label="单价" width="100" align="right">
          <template #default="scope">
            ¥{{ scope.row.unitPrice }}
          </template>
        </el-table-column>
        <el-table-column prop="totalAmount" label="总金额" width="120" align="right">
          <template #default="scope">
            ¥{{ scope.row.totalAmount }}
          </template>
        </el-table-column>
        <el-table-column prop="profit" label="利润" width="100" align="right">
          <template #default="scope">
            <span :class="{ 'profit-positive': scope.row.profit > 0, 'profit-negative': scope.row.profit < 0 }">
              ¥{{ scope.row.profit }}
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="customerName" label="客户姓名" width="120" />
        <el-table-column prop="customerPhone" label="客户电话" width="130" />
        <el-table-column prop="saleStatus" label="状态" width="100" align="center">
          <template #default="scope">
            <el-tag :type="scope.row.saleStatus === 1 ? 'success' : 'danger'">
              {{ scope.row.saleStatus === 1 ? '已完成' : '已取消' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="售卖时间" width="160">
          <template #default="scope">
            {{ formatTime(scope.row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150" fixed="right">
          <template #default="scope">
            <el-button
              type="primary"
              size="small"
              @click="showDetailDialog(scope.row)"
            >
              详情
            </el-button>
            <el-button
              v-if="scope.row.saleStatus === 1"
              type="danger"
              size="small"
              @click="handleCancel(scope.row)"
            >
              取消
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.size"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 添加售卖记录对话框 -->
    <el-dialog
      v-model="addDialogVisible"
      title="添加售卖记录"
      width="600px"
      :before-close="handleAddDialogClose"
    >
      <el-form
        ref="addFormRef"
        :model="addForm"
        :rules="addFormRules"
        label-width="100px"
      >
        <el-form-item label="选择商品" prop="storeProductId">
          <el-select
            v-model="addForm.storeProductId"
            placeholder="请选择商品"
            style="width: 100%"
            @change="handleProductChange"
          >
            <el-option
              v-for="product in productList"
              :key="product.id"
              :label="`${product.productName} (库存: ${product.currentStock})`"
              :value="product.id"
              :disabled="product.currentStock <= 0"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="售卖数量" prop="saleQuantity">
          <el-input-number
            v-model="addForm.saleQuantity"
            :min="1"
            :max="selectedProduct?.currentStock || 999"
            placeholder="请输入售卖数量"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="单价" prop="unitPrice">
          <el-input-number
            v-model="addForm.unitPrice"
            :min="0"
            :precision="2"
            placeholder="请输入单价"
            style="width: 100%"
          />
          <div class="form-tip" v-if="selectedProduct">
            建议售价: ¥{{ selectedProduct.sellingPrice }}
          </div>
        </el-form-item>
        <el-form-item label="客户姓名">
          <el-input
            v-model="addForm.customerName"
            placeholder="请输入客户姓名（可选）"
          />
        </el-form-item>
        <el-form-item label="客户电话">
          <el-input
            v-model="addForm.customerPhone"
            placeholder="请输入客户电话（可选）"
          />
        </el-form-item>
        <el-form-item label="备注">
          <el-input
            v-model="addForm.remark"
            type="textarea"
            :rows="3"
            placeholder="请输入备注（可选）"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleAddDialogClose">取消</el-button>
          <el-button type="primary" @click="handleAddSubmit" :loading="addSubmitting">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="售卖记录详情"
      width="600px"
    >
      <el-descriptions :column="2" border v-if="currentRecord">
        <el-descriptions-item label="记录编号">{{ currentRecord.recordNo }}</el-descriptions-item>
        <el-descriptions-item label="商品名称">{{ currentRecord.productName }}</el-descriptions-item>
        <el-descriptions-item label="商品编号">{{ currentRecord.productCode }}</el-descriptions-item>
        <el-descriptions-item label="售卖数量">{{ currentRecord.saleQuantity }}</el-descriptions-item>
        <el-descriptions-item label="单价">¥{{ currentRecord.unitPrice }}</el-descriptions-item>
        <el-descriptions-item label="总金额">¥{{ currentRecord.totalAmount }}</el-descriptions-item>
        <el-descriptions-item label="成本价">¥{{ currentRecord.costPrice }}</el-descriptions-item>
        <el-descriptions-item label="利润">
          <span :class="{ 'profit-positive': currentRecord.profit > 0, 'profit-negative': currentRecord.profit < 0 }">
            ¥{{ currentRecord.profit }}
          </span>
        </el-descriptions-item>
        <el-descriptions-item label="客户姓名">{{ currentRecord.customerName || '未填写' }}</el-descriptions-item>
        <el-descriptions-item label="客户电话">{{ currentRecord.customerPhone || '未填写' }}</el-descriptions-item>
        <el-descriptions-item label="状态">
          <el-tag :type="currentRecord.saleStatus === 1 ? 'success' : 'danger'">
            {{ currentRecord.saleStatus === 1 ? '已完成' : '已取消' }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="售卖时间">{{ formatTime(currentRecord.createTime) }}</el-descriptions-item>
        <el-descriptions-item label="备注" :span="2">{{ currentRecord.remark || '无' }}</el-descriptions-item>
      </el-descriptions>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Search } from '@element-plus/icons-vue'
import { getSalesRecordPage, addSalesRecord, cancelSalesRecord, exportSalesRecords } from '@/api/salesRecord'
import { getStoreProductList } from '@/api/storeProduct'

// 响应式数据
const loading = ref(false)
const addSubmitting = ref(false)
const tableData = ref([])
const productList = ref([])

// 搜索表单
const searchForm = reactive({
  recordNo: '',
  productName: '',
  customerName: '',
  saleStatus: null
})

// 分页
const pagination = reactive({
  page: 1,
  size: 10,
  total: 0
})

// 添加对话框
const addDialogVisible = ref(false)
const addFormRef = ref()
const addForm = reactive({
  storeProductId: null,
  saleQuantity: 1,
  unitPrice: null,
  customerName: '',
  customerPhone: '',
  remark: ''
})

const addFormRules = {
  storeProductId: [
    { required: true, message: '请选择商品', trigger: 'change' }
  ],
  saleQuantity: [
    { required: true, message: '请输入售卖数量', trigger: 'blur' }
  ],
  unitPrice: [
    { required: true, message: '请输入单价', trigger: 'blur' }
  ]
}

// 详情对话框
const detailDialogVisible = ref(false)
const currentRecord = ref(null)

// 计算属性
const selectedProduct = computed(() => {
  return productList.value.find(p => p.id === addForm.storeProductId)
})

// 方法
  const loadData = async () => {
    loading.value = true
    try {
      const params = {
        page: pagination.page,
        size: pagination.size,
        ...searchForm
      }
    const response = await getSalesRecordPage(params)
    if (response.code === 200) {
      tableData.value = response.data.records
      pagination.total = response.data.total
    } else {
      ElMessage.error(response.message || '查询失败')
    }
  } catch (error) {
    console.error('查询售卖记录失败:', error)
    ElMessage.error('查询失败')
  } finally {
    loading.value = false
  }
}

const loadProductList = async () => {
  try {
    const response = await getStoreProductList({ status: 1 }) // 只获取上架商品
    if (response.code === 200) {
      productList.value = response.data.records || response.data
    }
  } catch (error) {
    console.error('获取商品列表失败:', error)
  }
}

const handleSearch = () => {
  pagination.page = 1
  loadData()
}

const handleReset = () => {
  Object.assign(searchForm, {
    recordNo: '',
    productName: '',
    customerName: '',
    saleStatus: null
  })
  pagination.page = 1
  loadData()
}

const handleSizeChange = (size) => {
  pagination.size = size
  pagination.page = 1
  loadData()
}

const handleCurrentChange = (page) => {
  pagination.page = page
  loadData()
}

const showAddDialog = () => {
  loadProductList()
  addDialogVisible.value = true
}

const handleAddDialogClose = () => {
  addDialogVisible.value = false
  addFormRef.value?.resetFields()
  Object.assign(addForm, {
    storeProductId: null,
    saleQuantity: 1,
    unitPrice: null,
    customerName: '',
    customerPhone: '',
    remark: ''
  })
}

const handleProductChange = () => {
  if (selectedProduct.value) {
    addForm.unitPrice = selectedProduct.value.sellingPrice
  }
}

const handleAddSubmit = async () => {
  try {
    await addFormRef.value.validate()
    
    addSubmitting.value = true
    const response = await addSalesRecord(addForm)
    if (response.code === 200) {
      ElMessage.success('添加成功')
      handleAddDialogClose()
      loadData()
    } else {
      ElMessage.error(response.message || '添加失败')
    }
  } catch (error) {
    console.error('添加售卖记录失败:', error)
    ElMessage.error('添加失败')
  } finally {
    addSubmitting.value = false
  }
}

const showDetailDialog = (record) => {
  currentRecord.value = record
  detailDialogVisible.value = true
}

const handleCancel = async (record) => {
  try {
    await ElMessageBox.confirm(
      `确定要取消售卖记录"${record.recordNo}"吗？取消后将恢复商品库存。`,
      '确认取消',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    const response = await cancelSalesRecord(record.id)
    if (response.code === 200) {
      ElMessage.success('取消成功')
      loadData()
    } else {
      ElMessage.error(response.message || '取消失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('取消售卖记录失败:', error)
      ElMessage.error('取消失败')
    }
  }
}

const handleExport = async () => {
  try {
    const response = await exportSalesRecords(searchForm)
    if (response.code === 200) {
      // 这里可以实现导出功能，比如下载Excel文件
      ElMessage.success('导出成功')
      console.log('导出数据:', response.data)
    } else {
      ElMessage.error(response.message || '导出失败')
    }
  } catch (error) {
    console.error('导出失败:', error)
    ElMessage.error('导出失败')
  }
}

const formatTime = (time) => {
  if (!time) return ''
  return new Date(time).toLocaleString('zh-CN')
}

// 生命周期
onMounted(() => {
  loadData()
})
</script>

<style scoped>
.sales-record-management {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-form {
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}

.profit-positive {
  color: #67c23a;
  font-weight: bold;
}

.profit-negative {
  color: #f56c6c;
  font-weight: bold;
}

.form-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 5px;
}

.dialog-footer {
  text-align: right;
}
</style> 